package com.ron.pm.main.controller;

import com.ron.pm.account.dao.user.entities.User;
import com.ron.pm.account.service.user.UserService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *
 */
@RequestMapping(value = "/main")
@Controller
public class MainPageController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/gotoLoginPage.shtm")
    public ModelAndView gotoLoginPage(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @RequestMapping(value = "/login.shtm")
    public void login(String loginname, String password, HttpSession httpSession, HttpServletResponse response)throws IOException {
        PrintWriter out = response.getWriter();
        User user = userService.loginService(loginname,password);
        JSONObject jsonObject = new JSONObject();
        if(user == null){
            jsonObject.put("result","error");
        }else {
            jsonObject.put("result","success");
            httpSession.setAttribute("user",user);
        }
        out.print(jsonObject);
    }
    @RequestMapping("/gotoMainPage.shtm")
    public ModelAndView gotoMainPage(HttpSession httpSession){
        ModelAndView modelAndView  = new ModelAndView();
        //判断httpsession中的用户名密码是否存在于数据库中，如果存在则跳转至main.html。如果不存在则返回首页。
        if(httpSession == null){
            modelAndView.setViewName("index");
        }else {
            modelAndView.setViewName("main");
        }
        return modelAndView;
    }

}
